package login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author：徐志荣
 * @Date：2023/5/26 17:11
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //
       if(!username.equals("zhangsan")&& !username.equals("lisi") ){
            //登录失败
           System.out.println("登录失败,用户名错误");
           resp.sendRedirect("login.html");
           return;
       }
       if(!password.equals("123")){
           System.out.println("登录失败,密码错误");
           resp.sendRedirect("login.html");
           return;
       }
       //登陆成功
        //1.创建一个会话 ,存在就返回现成的,不存在就创建
        HttpSession session = req.getSession(true);

        //2.把当前的用户名保存到会话中 ,此处的 HttpSession又可以当成一个map使用
        session.setAttribute("username",username);
        //3.重定向到主页
        resp.sendRedirect("index");

    }
}
